package logT

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"
)

type Log struct {
	level string
	to    string
}

func (this *Log) Write(content string) {
	if this.to == "" {
		panic("config proifle error")
	} else if this.to == "stdout" {
		this.writeToStdout(content)
	} else {
		this.writeToFile(content)
	}
}

func (this *Log) writeToStdout(content string) {
	fmt.Fprintln(os.Stdout, time.Now(), this.level, content)
}

func (this *Log) writeToFile(content string) {
	f, err := os.OpenFile(this.to, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	fmt.Fprintln(f, time.Now(), this.level, content)
}

var Logger *Log = &Log{}

// 解析配置文件，config.profile
func init() {
	f, err := os.Open("/usr/local/goproject/src/go_code/project1/logT/config.profile")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	rd := bufio.NewReader(f)
	for {
		line, err := rd.ReadString('\n')
		if err != nil {
			break
		}
		if strings.HasPrefix(line, "#") {
			continue
		}
		line = strings.TrimSpace(line)
		str := strings.Split(line, "=")
		if str[0] == "level" {
			Logger.level = str[1]
		} else if str[0] == "to" {
			Logger.to = str[1]
		} else {
			break
		}
	}
}
